using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using WinformDevFramework.Services;
using WinformDevFramework.Services.System;

namespace WinformDevFramework
{
    public partial class Frmw_Receivable : BaseForm1
    {
        private Iw_ReceivableServices _w_ReceivableServices;
        private Iw_SettlementAccountServices _w_SettlementAccountServices;
        private IsysDicDataServices _sysDicDataServices;
        private Iw_CustomerServices _w_CustomerServices;
        private Iw_SaleServices _w_SaleServices;
        private Iw_ReceivableDetailServices _w_ReceivableDetailServices;
        private ISysUserServices _w_SysUserServices;
        public Frmw_Receivable(Iw_ReceivableServices w_ReceivableServices, Iw_SettlementAccountServices w_SettlementAccountServices, IsysDicDataServices sysDicDataServices, Iw_CustomerServices w_CustomerServices, Iw_SaleServices w_SaleServices, Iw_ReceivableDetailServices w_ReceivableDetailServices,ISysUserServices sysUserServices)
        {
            _w_ReceivableServices = w_ReceivableServices;
            InitializeComponent();
            _w_SettlementAccountServices = w_SettlementAccountServices;
            _sysDicDataServices = sysDicDataServices;
            _w_CustomerServices = w_CustomerServices;
            _w_SaleServices = w_SaleServices;
            _w_ReceivableDetailServices = w_ReceivableDetailServices;
            _w_SysUserServices= sysUserServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["ReceivableCode"].HeaderText = "收款单号";
            this.dataGridViewList.Columns["CustomerCode"].HeaderText = "客户编码";
            this.dataGridViewList.Columns["CustomerName"].HeaderText = "客户名称";
            this.dataGridViewList.Columns["ReceivableDate"].HeaderText = "收款日期";
            this.dataGridViewList.Columns["MakeUserID"].Visible = false;
            this.dataGridViewList.Columns["SettlementCode"].HeaderText = "结算账户编码";
            this.dataGridViewList.Columns["SettlementName"].HeaderText = "结算账户名称";
            this.dataGridViewList.Columns["SettlementType"].HeaderText = "结算方式";
            this.dataGridViewList.Columns["TotalPrice"].HeaderText = "实收金额";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";

            //设置结算方式
            SettlementType.DataSource = _sysDicDataServices.QueryListByClause(p => p.DicTypeID == 2004);
            SettlementType.DisplayMember = "DicData";
            SettlementType.ValueMember = "ID";

            //设置客户
            var customers = _w_CustomerServices.Query();
            CustomerName.DataSource = customers;
            CustomerName.DisplayMember = "CustomerName";
            CustomerName.ValueMember = "CustomerCode";
            CustomerName.SelectedIndexChanged += CustomerName_SelectedIndexChanged;

            //设置 结算账户
            var settlementAccount = _w_SettlementAccountServices.Query();
            SettlementName.DataSource = settlementAccount;
            SettlementName.DisplayMember = "Name";
            SettlementName.ValueMember = "Code";
            SettlementName.SelectedIndexChanged += SettlementName_SelectedIndexChanged;

            //设置制单人
            MakeUserID.DataSource = _w_SysUserServices.Query();
            MakeUserID.DisplayMember = "Fullname";
            MakeUserID.ValueMember = "ID";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        private void SettlementName_SelectedIndexChanged(object? sender, EventArgs e)
        {
            SettlementCode.Text = SettlementName.SelectedValue.ToString();
        }

        private void CustomerName_SelectedIndexChanged(object? sender, EventArgs e)
        {
            CustomerCode.Text = CustomerName.SelectedValue.ToString();
            SetDetailSale();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Receivable;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.ReceivableCode.Text = model.ReceivableCode.ToString();
            this.CustomerCode.Text = model.CustomerCode.ToString();
            this.CustomerName.Text = model.CustomerName.ToString();
            this.ReceivableDate.Text = model.ReceivableDate.ToString();
            this.MakeUserID.SelectedValue = model.MakeUserID;
            this.SettlementCode.Text = model.SettlementCode.ToString();
            this.SettlementName.Text = model.SettlementName.ToString();
            this.SettlementType.Text = model.SettlementType.ToString();
            this.TotalPrice.Text = model.TotalPrice.ToString();
            this.Remark.Text = model.Remark.ToString();
            SetDetailSale();
            SetDataToDetail(GetDetailData(model.ReceivableCode));

            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            var customers = _w_CustomerServices.Query();
            CustomerCode.Text = customers.First().CustomerCode;

            var settlementAccount = _w_SettlementAccountServices.Query();
            SettlementCode.Text = settlementAccount.First().Code;

            SetDetailSale();
            SetDataGridViewReadonlyStatus();
            MakeUserID.SelectedValue = AppInfo.User.ID;
        }
        /// <summary>
        /// 设置明细销售单下拉
        /// </summary>
        /// <param name="code"></param>
        private void SetDetailSale()
        {
            //设置 明细表中销售单号 获取该客户下未结清销售订单
            SaleCode.DataSource = _w_SaleServices.QueryListByClause(p => p.CustomerCode.Equals(CustomerCode.Text));
            SaleCode.ValueMember = "SaleCode";
            SaleCode.DisplayMember = "SaleCode";
        }
        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SetDataGridViewReadonlyStatus();
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_Receivable model = new w_Receivable();
                    // TODO获取界面的数据
                    if (string.IsNullOrEmpty(this.ReceivableCode.Text))
                    {
                        model.ReceivableCode = $"SK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.ReceivableCode = this.ReceivableCode.Text;
                    }
                    model.CustomerCode = this.CustomerCode.Text;
                    model.CustomerName = this.CustomerName.Text;
                    model.ReceivableDate = this.ReceivableDate.Value;
                    model.MakeUserID = this.MakeUserID.SelectedValue.ToInt32();
                    model.SettlementCode = this.SettlementCode.Text;
                    model.SettlementName = this.SettlementName.Text;
                    model.SettlementType = this.SettlementType.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.Remark = this.Remark.Text;

                    List<w_ReceivableDetail> details = new List<w_ReceivableDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_ReceivableDetail detail = new w_ReceivableDetail();
                            detail.SaleCode = row.Cells["SaleCode"].FormattedValue.ToString();
                            detail.Amount1 = row.Cells["Amount1"].FormattedValue.ToDecimal();
                            detail.Amount2 = row.Cells["Amount2"].FormattedValue.ToDecimal();
                            detail.Amount3 = row.Cells["Amount3"].FormattedValue.ToDecimal();
                            detail.Amount4 = row.Cells["Amount4"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    var id = _w_ReceivableServices.AddReceivableInfo(model, details);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        ReceivableCode.Text = model.ReceivableCode;
                        SetDataToDetail(GetDetailData(model.ReceivableCode));
                    }
                }
                // 修改
                else
                {
                    w_Receivable model = _w_ReceivableServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.ReceivableCode = this.ReceivableCode.Text;
                    model.CustomerCode = this.CustomerCode.Text;
                    model.CustomerName = this.CustomerName.Text;
                    model.ReceivableDate = this.ReceivableDate.Value;
                    model.MakeUserID = this.MakeUserID.SelectedValue.ToInt32();
                    model.SettlementCode = this.SettlementCode.Text;
                    model.SettlementName = this.SettlementName.Text;
                    model.SettlementType = this.SettlementType.Text;
                    model.TotalPrice = this.TotalPrice.Text.ToDecimal();
                    model.Remark = this.Remark.Text;
                    List<w_ReceivableDetail> details = new List<w_ReceivableDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_ReceivableDetail detail = new w_ReceivableDetail();
                            detail.SaleCode = row.Cells["SaleCode"].FormattedValue.ToString();
                            detail.ReceivableCode = row.Cells["ReceivableCodeD"].FormattedValue.ToString();
                            detail.ReceivableDetailCode = row.Cells["ReceivableDetailCode"].FormattedValue.ToString();

                            detail.Amount1 = row.Cells["Amount1"].FormattedValue.ToDecimal();
                            detail.Amount2 = row.Cells["Amount2"].FormattedValue.ToDecimal();
                            detail.Amount3 = row.Cells["Amount3"].FormattedValue.ToDecimal();
                            detail.Amount4 = row.Cells["Amount4"].FormattedValue.ToDecimal();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            details.Add(detail);
                        }
                    }
                    if (_w_ReceivableServices.UpdateReceivableInfo(model, details))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.ReceivableCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_ReceivableDetail> GetDetailData(string code)
        {
            List<w_ReceivableDetail> data = new List<w_ReceivableDetail>();
            data = _w_ReceivableDetailServices.QueryListByClause(p => p.ReceivableCode == code);
            return data;
        }

        /// <summary>
        /// 明细表 设置数据
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_ReceivableDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["ReceivableCodeD"].Value = p.ReceivableCode;
                row.Cells["ReceivableDetailCode"].Value = p.ReceivableDetailCode;
                row.Cells["SaleCode"].Value = p.SaleCode;
                row.Cells["Amount1"].Value = p.Amount1;
                row.Cells["Amount2"].Value = p.Amount2;
                row.Cells["Amount3"].Value = p.Amount3;
                row.Cells["Amount4"].Value = p.Amount4;
                row.Cells["RemarkD"].Value = p.Remark;
            });
        }
        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(ReceivableCode.Text));
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                if (_w_ReceivableServices.DeleteReceivableInfo(new w_Receivable()
                {
                    ID = txtID.Text.ToInt32(),
                    ReceivableCode = ReceivableCode.Text,
                    SettlementCode = SettlementCode.Text
                }))
                {
                    formStatus = FormStatus.Del;
                    SetToolButtonStatus(formStatus);
                    //列表重新赋值
                    dataGridViewDetail.Rows.Clear();
                    this.dataGridViewList.DataSource = GetData();
                }
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_Receivable> GetData()
        {
            List<w_Receivable> data = new List<w_Receivable>();
            data = _w_ReceivableServices.Query();
            return data;
        }


        /// <summary>
        /// 设置 明细表 销售单号选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "SaleCode" && dataGridViewDetail.Rows[e.RowIndex].Cells["SaleCode"].Value != null)
                {
                    string code = dataGridViewDetail.Rows[e.RowIndex].Cells["SaleCode"].Value.ToString();
                    var sale = _w_SaleServices.QueryByClause(p =>
                        p.SaleCode == code);
                    if (sale != null)
                    {
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount1"].Value = sale.TotalPrice;
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount2"].Value = sale.TotalPrice1;
                        dataGridViewDetail.Rows[e.RowIndex].Cells["Amount3"].Value = sale.TotalPrice2;

                    }
                }

                //汇总
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "Amount4")
                {
                    SetFormTotalData();
                }
            }
        }
        private void SetFormTotalData()
        {
            decimal total = 0;
            foreach (DataGridViewRow row in dataGridViewDetail.Rows)
            {
                if (!row.IsNewRow)
                {
                    total += row.Cells["Amount4"].Value.ToDecimal();
                }
            }
            TotalPrice.Text = total.ToString();
        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "SaleCode", "Amount4", "RemarkD" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
    }
}
